package com.stormragetech.sylwanas.process;

import com.stormragetech.sylwanas.util.Assert;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.connection.Connection;

/**
 * description: //TODO
 *
 * @author: Xue Bin
 * @version: 1.0.0-SNAPSHOT
 */
@Log4j2
public class MQConnCheck implements TreadExecutable {

    private MQOperationExector exector;
    private boolean stop;

    MQConnCheck(MQOperationExector exector) {
        Assert.notNull(exector, "MQOperationExector cannot be null !!!");
        this.exector = exector;
    }

    boolean isStop() {
        return stop;
    }

    @Override
    public void start() {
        log.info("[ SYSTEM - CHECK - START ] start rabbitmq connection check thread !!!");
        stop = false;
        new Thread(() -> {
            while (!stop) {
                try {
                    try {
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    log.info("[ SEND MAP SIZE ] - [ {} ]", exector.getCache().getSMap().size());
                    try {
                        Connection conn = exector.getFactory().createConnection();
                        if (conn.isOpen()) {
                            exector.start();
                            stop();
                        }
                    } catch (Exception e) {
                        continue;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public void stop() {
        this.stop = true;
        log.info("[ SYSTEM - CHECK - STOP ] stop rabbitmq connection check thread !!!");
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
